/**
Name: Nishant Kumar
Andrew Id: nkumar1
Course: 15-637
Date: 3/12/2012
**/

package edu.cmu.fithub.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.cmu.fithub.db.bean.User;

public class ImageServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	User user = (User) request.getAttribute("userImage");

        if (user == null || user.getImage() == null ) {
        	response.sendError(HttpServletResponse.SC_NOT_FOUND);
        	return;
        }
        
        response.setContentType("image");

        byte[] imageBytes;
		try {
			imageBytes = user.getImage().getBytes(1, (int) user.getImage().length());
		} catch (SQLException e) {
			// send custom image file
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
        	return;
		}
        
        ServletOutputStream out = response.getOutputStream();
        out.write(imageBytes);
    }
}
